package com.food.msgupdownbackend.application;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 测试微服务之间的通信
 * @author 24270
 */
@Service
public class RustTemplateService {
    /**
     * 不要删除new RestTemplate，不然会报错
     */
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = null;
    /**
     * 服务发现
     */
    private final DiscoveryClient discoveryClient;

    @Autowired
    public RustTemplateService(RestTemplate restTemplate, DiscoveryClient discoveryClient) throws UnsupportedEncodingException {
        this.restTemplate = restTemplate;
        this.discoveryClient = discoveryClient;
    }

    public void uploadImgWithAliment(String id, List<String> imgList) {
        // 获取服务实例
        ServiceInstance serviceInstance = discoveryClient.getInstances("food-msg-management").get(0);
        System.out.println(serviceInstance.toString());
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String serviceUrl = "http://" + host + ":" + port + "/aliment/addImg";
        System.out.println(serviceUrl);

        MultiValueMap map = new LinkedMultiValueMap();
        map.add("id", id);
        map.add("imgUrl", imgList);

        System.out.println(map.toString());
        responseEntity = restTemplate.postForEntity(serviceUrl, map, String.class);
    }
}
